// pages/map/map.js
const app = getApp();

Page({
  data: {
    subKey: 'WASBZ-45IE7-ZQTXX-PPC4F-6D2MF-WPB4Z',
    // 地图控制选项
    mapOptions: {
      enable3d: false,
      showLocation: true,
      showCompass: false,
      enableOverlooking: false,
      enableZoom: true,
      enableScroll: true,
      enableRotate: false,
      enableSatellite: false,
      enableTraffic: false
    },
    // 地图中心点
    latitude: 30.873496,
    longitude: 120.131063,
    scale: 16,
    // 地图元素
    markers: [],
    circles: [],
    polylines: [],
    polygons: [],
    // 景点详情弹窗
    showDetail: false,
    selectedPoint: null,
    // 加载状态
    loading: false,
    error: null
  },

  onLoad(options) {
    this.loadPointsData();
  },

  // 从API加载景点数据
  loadPointsData() {
    this.setData({ loading: true });
    
    wx.request({
      url: app.globalData.pointsapi,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200 && res.data) {
          const points = res.data || [];
          this.processPointsData(points);
        } else {
          this.setData({ error: '获取数据失败' });
        }
      },
      fail: (err) => {
        console.error('API请求失败:', err);
        this.setData({ error: '网络连接错误' });
      },
      complete: () => {
        this.setData({ loading: false });
      }
    });
  },

  // 处理景点数据并转换为标记点
  processPointsData(points) {
    const markers = points.map(point => ({
      id: point.fid,
      latitude: point.geometry.coordinates[1], // 注意经纬度顺序
      longitude: point.geometry.coordinates[0],
      iconPath: '../../assets/images/location.png',
      width: 24,
      height: 24,
      label: {
        content: point.name,
        color: '#000000',
        bgColor: '#ffffff',
        padding: 4,
        borderRadius: 4,
        display: 'ALWAYS'
      },
      // 自定义数据可以传递到事件处理函数
      data: point
    }));

    this.setData({ markers });
  },

  // 标记点点击事件
  onMarkerTap(e) {
    const markerId = e.markerId;
    const marker = this.data.markers.find(m => m.id === markerId);
    
    if (marker) {
      this.setData({
        showDetail: true,
        selectedPoint: marker.data
      });
    }
  },

  // 关闭详情弹窗
  closeDetail() {
    this.setData({
      showDetail: false
    });
  },

  // 定位到当前位置
  locateToCurrent() {
    
  },

  // 切换地图类型
  toggleMapType() {
    this.setData({
      'mapOptions.enableSatellite': !this.data.mapOptions.enableSatellite
    });
  }
});